package com.ssly.weixin.xichang.home.controller;

import com.ssly.weixin.xichang.common.domain.Report;
import com.ssly.weixin.xichang.common.domain.VerifyCode;
import com.ssly.weixin.xichang.common.repository.ReportRepository;
import com.ssly.weixin.xichang.common.repository.VerifyCodeRepository;
import com.ssly.weixin.xichang.util.Helper;
import com.ssly.weixin.xichang.util.JsonResult;
import com.ssly.weixin.xichang.util.R;
import com.ssly.weixin.xichang.util.SMS;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.NoSuchElementException;

@Controller("home")
@RequestMapping("/")
public class IndexController {
    @Value("${ssly.upload.dir}")
    private String uploadDir;
    @Autowired
    private ReportRepository reportRepository;
    @Autowired
    private VerifyCodeRepository verifyCodeRepository;

    //    显示提交页面
    @GetMapping
    public String index() {
        return "home/index";
    }
    //    显示提交页面
    @GetMapping("weixin-article")
    public String weixin() {
        return "weixin-article/index";
    }
    @GetMapping("weixin-article/detail")
    public String show() {
        return "weixin-article/detail";
    }

    //    提交
    @PostMapping
    @ResponseBody
    public JsonResult submit(Report report,
                             @RequestParam("verifyCode") String code,
                             @RequestParam(value = "pictureFile1", required = false) MultipartFile pictureFile1,
                             @RequestParam(value = "pictureFile2", required = false) MultipartFile pictureFile2,
                             @RequestParam(value = "pictureFile3", required = false) MultipartFile pictureFile3,
                             @RequestParam(value = "pictureFile4", required = false) MultipartFile pictureFile4,
                             @RequestParam(value = "videoFile1", required = false) MultipartFile videoFile1,
                             @RequestParam(value = "videoFile2", required = false) MultipartFile videoFile2,
                             @RequestParam(value = "videoFile3", required = false) MultipartFile videoFile3,
                             @RequestParam(value = "videoFile4", required = false) MultipartFile videoFile4) {
        ArrayList<String> pictureFileNames = new ArrayList<>();
        ArrayList<String> videoFileNames = new ArrayList<>();

        try {
            VerifyCode verifyCode = verifyCodeRepository.findTopByPhoneOrderByCreateTimeDesc(report.getPhone()).get();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
//            String saveDir = uploadDir+ File.separator+simpleDateFormat.format(System.currentTimeMillis());
            File file=new File(uploadDir,simpleDateFormat.format(System.currentTimeMillis()));
            boolean mkdir = file.mkdir();
            String saveDir=file.getAbsolutePath();

            if (code.equals(verifyCode.getCode())) {
                String pictureFile1Name = Helper.uploadFile(pictureFile1, saveDir);
                String pictureFile2Name = Helper.uploadFile(pictureFile2, saveDir);
                String pictureFile3Name = Helper.uploadFile(pictureFile3, saveDir);
                String pictureFile4Name = Helper.uploadFile(pictureFile4, saveDir);
                if (null != pictureFile1Name) {
                    pictureFileNames.add(pictureFile1Name);
                }
                if (null != pictureFile2Name) {
                    pictureFileNames.add(pictureFile2Name);
                }
                if (null != pictureFile3Name) {
                    pictureFileNames.add(pictureFile3Name);
                }
                if (null != pictureFile4Name) {
                    pictureFileNames.add(pictureFile4Name);
                }

                String videoFile1Name = Helper.uploadFile(videoFile1, saveDir);
                String videoFile2Name = Helper.uploadFile(videoFile2, saveDir);
                String videoFile3Name = Helper.uploadFile(videoFile3, saveDir);
                String videoFile4Name = Helper.uploadFile(videoFile4, saveDir);

                if (null != videoFile1Name) {
                    videoFileNames.add(videoFile1Name);
                }
                if (null != videoFile2Name) {
                    videoFileNames.add(videoFile2Name);
                }
                if (null != videoFile3Name) {
                    videoFileNames.add(videoFile3Name);
                }
                if (null != videoFile4Name) {
                    videoFileNames.add(videoFile4Name);
                }

                report.setPictures(new JSONArray(pictureFileNames).toString());
                report.setVideos(new JSONArray(videoFileNames).toString());
                report.setCreateTime(new Timestamp(System.currentTimeMillis() + 10 * 60 * 1000));
                report.setStatus(0);
                report.setView(0);
                reportRepository.save(report);
                return R.success("感谢您参与监督！请保持电话畅通，我们将在24小时内与您联系！");
            } else {
                return R.error("验证码错误");
            }

        } catch (NoSuchElementException e) {
            e.printStackTrace();
            return R.error("验证码错误");
        } catch (IOException e) {
            return R.error("文件上传失败");
        }

    }

    //    获取验证码
    @GetMapping("getVerifyCode")
    @ResponseBody
    public JsonResult getVerifyCode(@RequestParam String phone) {
        SMS sms = new SMS();
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        VerifyCode verifyCode = new VerifyCode();
        verifyCode.setPhone(phone);
        verifyCode.setCode(code);
        verifyCode.setStatus(0);
        verifyCode.setCreateTime(new Timestamp(System.currentTimeMillis()));
        verifyCode.setExpireTime(new Timestamp(System.currentTimeMillis() + 10 * 60 * 1000));
        String content = "您好，欢迎使用短信验证功能，您的手机验证码是：" + code + "，10分钟内有效。";

        boolean send = sms.send(phone, content);

        if (!Helper.checkPhone(phone)) {
            return R.error("手机号错误");
        }
        if (send) {
            verifyCodeRepository.save(verifyCode);
            return R.success("短信发送成功");
        }
        return R.error("短信发送失败,请稍后再试");
    }


}
